<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>博客系统</title>
    <!-- 引入Element UI -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/display.css">
    <script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
        }
        </style>
</head>
<body>
    <div id="app">
        <el-container style="height: 100vh;">
            <el-aside width="220px" style="background-color: #545c64;">
                <div style="color: #fff; padding: 20px; font-size: 18px; text-align: center;">
                    {{username}} 的管理后台
                </div>
                <el-menu
                    default-active="1"
                    background-color="#545c64"
                    text-color="#fff"
                    active-text-color="#ffd04b"
                    style="border-right: none;">
                    <el-menu-item index="1" @click="activeTab = 'users'">
                        <i class="el-icon-user"></i>
                        <span>用户管理</span>
                    </el-menu-item>
                    <el-menu-item index="2" @click="activeTab = 'posts'">
                        <i class="el-icon-document"></i>
                        <span>帖子管理</span>
                    </el-menu-item>
                    <el-menu-item index="3" @click="activeTab = 'comments'">
                        <i class="el-icon-chat-dot-round"></i>
                        <span>评论管理</span>
                    </el-menu-item>
                    <el-menu-item index="4" @click="logout">
                        <i class="el-icon-switch-button"></i>
                        <span>登出</span>
                    </el-menu-item>
                </el-menu>
            </el-aside>

            <el-main style="padding: 20px; background-color: #f0f2f5;">
                <!-- 搜索和新增区域 -->
                <div style="margin-bottom: 20px;">
                    <el-input v-model="searchQuery" placeholder="搜索..." style="width: 300px; margin-right: 10px;"></el-input>
                    <el-button type="primary" @click="search">搜索</el-button>
                    <el-button type="success" @click="showAddDialog" style="float: right;">新增</el-button>
                </div>

                <!-- 用户管理 -->
                <div v-if="activeTab === 'users'">
                    <el-table :data="filteredUsers" style="width: 100%">
                        <el-table-column prop="username" label="用户名"></el-table-column>
                        <el-table-column prop="email" label="邮箱"></el-table-column>
                        <el-table-column prop="role" label="角色"></el-table-column>
                        <el-table-column label="状态">
                            <template slot-scope="scope">
                                <el-tag :type="scope.row.status ? 'success' : 'danger'">
                                    {{ scope.row.status ? '正常' : '封禁' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="250">
                            <template slot-scope="scope">
                                <el-button size="mini" @click="editItem(scope.row, 'user')">编辑</el-button>
                                <el-button size="mini" type="danger" @click="deleteItem(scope.row.id, 'user')">删除</el-button>
                                <el-button size="mini" v-if="scope.row.status" @click="toggleStatus(scope.row.id, 'user', false)">封禁</el-button>
                                <el-button size="mini" v-else @click="toggleStatus(scope.row.id, 'user', true)">解封</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <!-- 帖子管理 -->
                <div v-if="activeTab === 'posts'">
                    <el-table :data="filteredPosts" style="width: 100%">
                        <el-table-column prop="title" label="标题"></el-table-column>
                        <el-table-column prop="content" label="内容" width="300"></el-table-column>
                        <el-table-column prop="author" label="作者"></el-table-column>
                        <el-table-column label="状态">
                            <template slot-scope="scope">
                                <el-tag :type="scope.row.status ? 'success' : 'danger'">
                                    {{ scope.row.status ? '正常' : '封禁' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="250">
                            <template slot-scope="scope">
                                <el-button size="mini" @click="editItem(scope.row, 'post')">编辑</el-button>
                                <el-button size="mini" type="danger" @click="deleteItem(scope.row.id, 'post')">删除</el-button>
                                <el-button size="mini" v-if="scope.row.status" @click="toggleStatus(scope.row.id, 'post', false)">封禁</el-button>
                                <el-button size="mini" v-else @click="toggleStatus(scope.row.id, 'post', true)">解封</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <!-- 评论管理 -->
                <div v-if="activeTab === 'comments'">
                    <el-table :data="filteredComments" style="width: 100%">
                        <el-table-column prop="content" label="内容" width="300"></el-table-column>
                        <el-table-column prop="author" label="作者"></el-table-column>
                        <el-table-column label="所属帖子">
                            <template slot-scope="scope">
                                {{ scope.row.post_title || '[无标题]' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="状态">
                            <template slot-scope="scope">
                                <el-tag :type="scope.row.status ? 'success' : 'danger'">
                                    {{ scope.row.status ? '正常' : '封禁' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="250">
                            <template slot-scope="scope">
                                <el-button size="mini" @click="editItem(scope.row, 'comment')">编辑</el-button>
                                <el-button size="mini" type="danger" @click="deleteItem(scope.row.id, 'comment')">删除</el-button>
                                <el-button size="mini" v-if="scope.row.status" @click="toggleStatus(scope.row.id, 'comment', false)">封禁</el-button>
                                <el-button size="mini" v-else @click="toggleStatus(scope.row.id, 'comment', true)">解封</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-main>
            </el-main>
        </el-container>


        <!-- 新增对话框 -->
        <el-dialog :title="`新增${this.activeTab === 'users' ? '用户' : this.activeTab === 'posts' ? '帖子' : '评论'}`"
                  :visible.sync="addDialogVisible" width="50%">
            <el-form :model="addForm" label-width="100px">
                <el-form-item label="用户名" v-if="activeTab === 'users'">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" v-if="activeTab === 'users'">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="密码" v-if="activeTab === 'users'">
                    <el-input v-model="addForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="标题" v-if="activeTab === 'posts'">
                    <el-input v-model="addForm.title"></el-input>
                </el-form-item>
                <el-form-item label="内容" v-if="activeTab !== 'users'">
                    <el-input type="textarea" v-model="addForm.content" rows="5"></el-input>
                </el-form-item>
                <el-form-item label="帖子ID" v-if="activeTab === 'comments'">
                    <el-input v-model="addForm.postId"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addItem">确定</el-button>
            </span>
        </el-dialog>
    </div>

    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    activeTab: 'users',
                    searchQuery: '',
                    users: [],
                    posts: [],
                    comments: [],
                    username: '管理员',
                    token: localStorage.getItem('token') || '',
                    isAdmin: true,

                    // 新增表单数据
                    addForm: {
                        type: 'user',
                        username: '',
                        email: '',
                        password: '',
                        title: '',
                        content: '',
                        postId: ''
                    },
                    addDialogVisible: false
                }
            },
            created() {
                if (!this.token) {
                    this.$message.error('请先登录');
                    this.logout();
                    return;
                }

                this.fetchUserInfo().then(() => {
                    this.loadAllData();
                }).catch(() => {
                    this.logout();
                });
            },

            computed: {
                filteredUsers() {
                    if (!this.searchQuery) return this.users;
                    return this.users.filter(user =>
                        user.username.includes(this.searchQuery) ||
                        user.email.includes(this.searchQuery)
                    );
                },
                filteredPosts() {
                    if (!this.searchQuery) return this.posts;
                    return this.posts.filter(post =>
                        post.title.includes(this.searchQuery) ||
                        post.content.includes(this.searchQuery)
                    );
                },
                filteredComments() {
                    if (!this.searchQuery) return this.comments;
                    return this.comments.filter(comment =>
                        comment.content.includes(this.searchQuery)
                    );
                }
            },

            methods: {
                loadAllData() {
                    this.loadUsers();
                    this.loadPosts();
                    this.loadComments();
                },

                loadUsers() {
                    axios.get('/admin/users', {
                        headers: {
                            'Authorization': `Bearer ${this.token}`
                        }
                    })
                    .then(response => {
                        this.users = response.data.users;
                    })
                    .catch(error => {
                        this.$message.error('加载用户失败');
                    });
                },

                loadPosts() {
                    axios.get('/admin/posts', {
                        headers: {
                            'Authorization': `Bearer ${this.token}`
                        }
                    })
                    .then(response => {
                        this.posts = response.data.posts;
                    })
                    .catch(error => {
                        this.$message.error('加载帖子失败');
                    });
                },

                loadComments() {
                    axios.get('/admin/comments', {
                        headers: {
                            'Authorization': `Bearer ${this.token}`
                        }
                    })
                    .then(response => {
                        console.log('Comments API response:', response.data);
                        this.comments = response.data.comments.map(comment => {
                            return {
                                ...comment,
                                post_title: comment.post_title || '[已删除]'
                            };
                        });
                    })
                    .catch(error => {
                        this.$message.error('加载评论失败');
                    });
                },

                showAddDialog() {
                    this.addForm = {
                        type: this.activeTab,
                        username: '',
                        email: '',
                        password: '',
                        title: '',
                        content: '',
                        postId: ''
                    };
                    this.addDialogVisible = true;
                },

                addItem() {
                    // 表单验证
                    if (this.activeTab === 'users') {
                        if (!this.addForm.username || !this.addForm.email || !this.addForm.password) {
                            this.$message.error('请填写完整用户信息');
                            return;
                        }
                    } else if (this.activeTab === 'posts') {
                        if (!this.addForm.title || !this.addForm.content) {
                            this.$message.error('请填写完整帖子信息');
                            return;
                        }
                    } else if (this.activeTab === 'comments') {
                        if (!this.addForm.postId || !this.addForm.content) {
                            this.$message.error('请填写完整评论信息');
                            return;
                        }
                    }

                    const loading = this.$loading({
                        lock: true,
                        text: '正在提交...',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });

                    let apiUrl, requestData;
                    try {
                        console.log('Current activeTab:', this.activeTab);
                        console.log('Form data:', this.addForm);

                        let apiUrl, requestData;
                        const type = this.activeTab; // 确保使用当前activeTab

                        if (type === 'users') {
                            apiUrl = '/admin/users';
                            requestData = {
                                username: this.addForm.username,
                                email: this.addForm.email,
                                password: this.addForm.password,
                                role: 'admin'
                            };
                        } else if (type === 'posts') {
                            apiUrl = '/posts';
                            requestData = {
                                title: this.addForm.title,
                                content: this.addForm.content
                            };
                        } else if (type === 'comments') {
                            apiUrl = '/admin/comments';
                            requestData = {
                                content: this.addForm.content,
                                post_id: this.addForm.postId
                            };
                        } else {
                            throw new Error(`未知的类型: ${type}`);
                        }

                        if (!apiUrl || !requestData) {
                            throw new Error('API URL或请求数据未正确初始化');
                        }

                        console.log('准备发送请求到:', apiUrl, '数据:', requestData);

                        axios.post(apiUrl, requestData, {
                            headers: {
                                'Authorization': `Bearer ${this.token}`
                            }
                        }).then(response => {
                            console.log('Response received:', response);
                            this.$message.success('添加成功');
                            this.addDialogVisible = false;
                            this.loadAllData();
                        }).catch(error => {
                            console.error('Request failed:', error);
                            let errorMsg = '添加失败';
                            if (error.response) {
                                errorMsg = error.response.data.message ||
                                          error.response.data.error ||
                                          errorMsg;
                                if (error.response.status === 401) {
                                    errorMsg = '未授权，请重新登录';
                                    this.logout();
                                }
                            }
                            this.$message.error(errorMsg);
                        }).finally(() => {
                            loading.close();
                        });
                    } catch (error) {
                        loading.close();
                        console.error('Unexpected error:', error);
                        this.$message.error('发生未知错误');
                    }
                },

                search() {
                    const type = this.activeTab;
                    const params = {
                        search: this.searchQuery,
                        page: 1,
                        per_page: 10
                    };

                    let apiUrl = '';
                    if (type === 'users') {
                        apiUrl = '/admin/users';
                    } else if (type === 'posts') {
                        apiUrl = '/posts';
                    } else if (type === 'comments') {
                        apiUrl = '/admin/comments';
                    }

                    axios.get(apiUrl, {
                        params,
                        headers: {
                            'Authorization': `Bearer ${this.token}`
                        }
                    })
                    .then(response => {
                        if (type === 'users') {
                            this.users = response.data.users;
                        } else if (type === 'posts') {
                            this.posts = response.data.posts;
                        } else if (type === 'comments') {
                            this.comments = response.data.comments;
                        }
                        this.$message.success('搜索成功');
                    })
                    .catch(error => {
                        this.$message.error(error.response?.data?.message || '搜索失败');
                    });
                },

                editItem(row, type) {
                    this.$prompt('请输入新的内容', '编辑', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        inputValue: type === 'user' ? row.username :
                                   type === 'post' ? row.title :
                                   row.content,
                        inputPattern: /.+/,
                        inputErrorMessage: '内容不能为空'
                    }).then(({ value }) => {
                        const loading = this.$loading({
                            lock: true,
                            text: '正在保存...',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.7)'
                        });

                        let url = '';
                        let data = {};

                        if (type === 'user') {
                            url = `/admin/users/${row.id}`;
                            data = { username: value };
                        } else if (type === 'post') {
                            url = `/admin/posts/${row.id}`;
                            data = { title: value };
                        } else {
                            url = `/admin/comments/${row.id}`;
                            data = { content: value };
                        }

                        axios.put(url, data, {
                            headers: {
                                'Authorization': `Bearer ${this.token}`
                            }
                        }).then(() => {
                            this.$message.success('编辑成功');
                            this.loadAllData();
                        }).catch(error => {
                            this.$message.error(error.response?.data?.message || '编辑失败');
                        }).finally(() => {
                            loading.close();
                        });
                    }).catch(() => {
                        this.$message.info('已取消编辑');
                    });
                },

                toggleStatus(id, type, status) {
                    const urlMap = {
                        user: `/admin/users/${id}/${status ? 'unban' : 'ban'}`,
                        post: `/admin/posts/${id}/${status ? 'unban' : 'ban'}`,
                        comment: `/admin/comments/${id}/${status ? 'unban' : 'ban'}`
                    };

                    axios.put(urlMap[type], {}, {
                        headers: {
                            'Authorization': `Bearer ${this.token}`
                        }
                    })
                    .then(() => {
                        this.$message.success(status ? '已解封' : '已封禁');
                        this.loadAllData();
                    })
                    .catch(error => {
                        this.$message.error(error.response.data.message || '操作失败');
                    });
                },

                deleteItem(id, type) {
                    this.$confirm('确定要删除吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        const urlMap = {
                            user: `/admin/users/${id}`,
                            post: `/admin/posts/${id}`,
                            comment: `/admin/comments/${id}`
                        };

                        axios.delete(urlMap[type], {
                            headers: {
                                'Authorization': `Bearer ${this.token}`
                            }
                        })
                        .then(() => {
                            this.$message.success('删除成功');
                            this.loadAllData();
                        })
                        .catch(error => {
                            this.$message.error(error.response.data.message || '删除失败');
                        });
                    }).catch(() => {
                        this.$message.info('已取消删除');
                    });
                },

                fetchUserInfo() {
                    return new Promise((resolve, reject) => {
                        axios.get('/user', {
                            headers: {
                                'Authorization': `Bearer ${this.token}`
                            }
                        })
                        .then(response => {
                            if (!response.data || !response.data.username) {
                                throw new Error('无效的用户信息');
                            }
                            this.username = response.data.username;
                            resolve();
                        })
                        .catch(error => {
                            this.$message.error('获取用户信息失败');
                            reject(error);
                        });
                    });
                },

                logout() {
                    // 清除本地存储
                    localStorage.removeItem('token');

                    // 清除cookie
                    document.cookie = 'token=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';

                    // 重置状态
                    this.token = '';
                    this.username = '';

                    // 跳转到登录页
                    this.$message.success('已登出');
                    window.location.href = '/login';
                }
            }
        });
    </script>
</body>
</html>